package org.mcflier.appuntamento.io.driver.rss.torrent;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import org.gnu.stealthp.rsslib.RSSHandler;
import org.gnu.stealthp.rsslib.RSSItem;
import org.mcflier.appuntamento.core.exception.ModulesException;
import org.mcflier.appuntamento.data.model.Torrent;
import org.mcflier.appuntamento.data.model.TorrentCategory;
import org.mcflier.appuntamento.data.model.TorrentList;
import org.mcflier.appuntamento.io.driver.rss.RssTools;
import org.mcflier.appuntamento.io.exception.RSSConnectionException;
import org.mcflier.appuntamento.io.exception.RSSParsingException;

public class RssKickAssDriver extends AbstractRssTorrentDriver {
	
	public static final String CONTENTLENGTH_TAG = "torrent:contentLength";
	public static final String INFOHASH_TAG = "torrent:infoHash";
	public static final String MAGNETURI_TAG = "torrent:magnetURI";
	public static final String VERIFIED_TAG = "torrent:verified";
	
	public RssKickAssDriver() throws ModulesException {
		super();
	}

	@Override
	public Torrent readTorrent(RSSItem item) {
		TorrentCategory category = null;
		if(item.getUnknownField(RSSHandler.CATEGORY_TAG)==null) category = TorrentCategory.UNDEFINED_CATEGORY;
		else if(item.getUnknownField(RSSHandler.CATEGORY_TAG).contains("HD")) category = TorrentCategory.HD_CATEGORY;
		else if(item.getUnknownField(RSSHandler.CATEGORY_TAG).contains("SD")) category = TorrentCategory.SD_CATEGORY;
		else category = TorrentCategory.UNDEFINED_CATEGORY;
		
		Torrent torrent = new Torrent(
				item.getTitle(),
				item.getUnknownField(MAGNETURI_TAG),
				category,
				this.getSource());
		torrent.setWeblink(item.getUnknownField(GUID_TAG));
		torrent.setPubDate(RssTools.convertToTimestamp(item.getPubDate()));
		String author = null;
		try{
			author = item.getAuthor();
			if(author.endsWith("/"))
				author = author.substring(0, author.lastIndexOf("/"));
			
			StringTokenizer tokens = new StringTokenizer(author, "/");
			author = author.split("/")[tokens.countTokens()];
		}
		catch(NullPointerException e){}
		torrent.setGuid(item.getUnknownField(GUID_TAG));
		torrent.setVerified(item.getUnknownField(VERIFIED_TAG).trim().equals("1")?true:false);
		
		try {
			torrent.setContentLength(Long.valueOf(item.getUnknownField(CONTENTLENGTH_TAG)));
		} catch (NumberFormatException e) {
			this.logger.warning("Element: '"+torrent.getTitle()+"' has an invalid content length. Set it to -1");
			torrent.setContentLength(-1);
		}
		torrent.setInfoHash(item.getUnknownField(INFOHASH_TAG));
		torrent.setMagnetUri(item.getUnknownField(MAGNETURI_TAG));

		return torrent;
	}
	@Override
	public List<TorrentList> getHDTorrents() throws RSSConnectionException, RSSParsingException {
		this.logger.info("Getting HD rss list from Pirate Bay");
		return this.getHDTorrents(new Timestamp(0));
	}

	@Override
	public List<TorrentList> getHDTorrents(Timestamp since) throws RSSConnectionException, RSSParsingException {
		this.logger.info("Getting HD rss list from Pirate Bay since "+since);

		List<TorrentList> torrents = new ArrayList<TorrentList>();
		TorrentList list;
		List<String> hdResources = this.getSource().getHDSources();
		for (String resource : hdResources) {
			torrents.add(this.getList(resource, since));
		}

		return torrents;
	}

	@Override
	public List<TorrentList> getSDTorrents() throws RSSConnectionException, RSSParsingException {
		this.logger.info("Getting SD rss list from Pirate Bay");
		return this.getSDTorrents(new Timestamp(0));
	}

	@Override
	public List<TorrentList> getSDTorrents(Timestamp since) throws RSSConnectionException, RSSParsingException {
		this.logger.info("Getting SD rss list from Pirate Bay since "+since);

		List<TorrentList> torrents = new ArrayList<TorrentList>();
		TorrentList list;
		List<String> sdResources = this.getSource().getSDSources();
		for (String resource : sdResources) {
			torrents.add(this.getList(resource, since));
		}

		return torrents;
	}

	@Override
	public List<TorrentList> getUndefinedTorrents() throws RSSConnectionException, RSSParsingException {
		this.logger.info("Getting undefined quality rss list from Pirate Bay");
		return this.getUndefinedTorrents(new Timestamp(0));
	}

	@Override
	public List<TorrentList> getUndefinedTorrents(Timestamp since) throws RSSConnectionException, RSSParsingException {
		this.logger.info("Getting undefined quality rss list from Pirate Bay since "+since);

		List<TorrentList> torrents = new ArrayList<TorrentList>();
		TorrentList list;
		List<String> notClResources = this.getSource().getNotClassifSources();
		for (String resource : notClResources) {
			torrents.add(this.getList(resource, since));
		}

		return torrents;
	}
}